import vlc
 
source_mainstream = "rtsp://192.168.0.123:554/live/mainstream"

import vlc

class Recorder:
    def __init__(self):         
        self.instance = vlc.Instance("--no-xlib")
    
    def start(self, stream, output_file):
        try:
            
            self.record_player = self.instance.media_player_new()
            self.media = self.instance.media_new(stream)  # 修改输入源

            # 简化转码配置
            sout = f":sout=#transcode{{vcodec=h264}}:std{{access=file,mux=mp4,dst={output_file}}}"
            # 增加 sout-mux-caching 的值
            caching = 200000   # 可根据实际情况调整
            self.media.add_option(f":sout-mux-caching={caching}")
            self.media.add_option(sout)
            self.record_player.set_media(self.media)

            s = self.record_player.play()
            if s == -1:
                print("播放失败，请检查输入流或编解码器。")
            else:
                print("录制开始...")
             
            return True
        except Exception as e:
            print(e)
            
            if self.media:
                self.media.release()
                self.media = None
            if self.record_player:
                self.record_player.stop()
                self.record_player = None

            return False

    def stop(self):
        self.record_player.stop()
        self.record_player = None
        
        self.media.release()
        self.media = None

        print("录制停止，文件已保存。")

if __name__ == "__main__":

    v = vlc.libvlc_get_version()
    print(v)

    recorder = Recorder()
    recorder.start(source_mainstream, "manual_record3.mp4")
    
    input("按 Enter 键停止录制...")
    recorder.stop()